﻿using PwdCookie.App_Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace PwdCookie.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// 用户登录页
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            if (SqlHelper.GetCookieValue("NameCookie") != "" && SqlHelper.GetCookieValue("PwdCookie") != "")
            {
                //获取Cookie
                string name = SqlHelper.GetCookieValue("NameCookie");
                string pwd = SqlHelper.GetCookieValue("PwdCookie");

                //使用Decode（）解密
                ViewBag.UserName = SqlHelper.Decode(name);
                ViewBag.Pwd = SqlHelper.Decode(pwd);
            }
            return View();
        }

        /// <summary>
        /// 接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string ToLogin()
        {
            //获取Post数据（application/json格式须用流获取）
            string jsonPrameters = "";
            Stream stream = Request.InputStream;
            if (stream.Length != 0)
            {
                StreamReader streamReader = new StreamReader(stream);
                jsonPrameters = streamReader.ReadToEnd();
            }

            Dictionary<string, string> dic = SqlHelper.GetDictionaryByJson(jsonPrameters);
            string UserName = dic["UserName"];
            string Pwd = dic["Pwd"];
            int Status = Convert.ToInt32(dic["Status"]);

            //判断是否记住密码，记住则将登录信息放入至Cookies中
            if (Status == 1)
            {
                //创建Cookie【防止登录信息泄露，这里使用Encode()将信息进行了加密】
                SqlHelper.SetCookie("NameCookie", SqlHelper.Encode(UserName), DateTime.Now.AddDays(7));
                SqlHelper.SetCookie("PwdCookie", SqlHelper.Encode(Pwd), DateTime.Now.AddDays(7));
            }

            string result = "{\"UserName\":\"" + UserName + "\",\"Pwd\":\"" + Pwd + "\"}";
            return result;
        }

        /// <summary>
        /// 清空登录信息【删除Cookie】
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string ClearLogin()
        {
            //删除Cookie
            SqlHelper.RemoveCookie("NameCookie");
            SqlHelper.RemoveCookie("PwdCookie");

            //删除后获取Cookie查看是否已删除
            string result = "";
            if (SqlHelper.GetCookieValue("NameCookie") == "")
            {
                result = "{\"result\":true}";
            }
            else
            {
                result = "{\"result\":false}";
            }
            return result;
        }

        /// <summary>
        /// 程序首页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult IndexAdmin()
        {
            return View();
        }
    }
}